package org.example.design.memo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Classname Admin
 * @Description 管理者类
 * @Date 2020/11/10 3:08 下午
 * @Created by xiangjd
 */
public class Admin {
    private int cursorIdx = 0;

    private List<ConfigMemento> mementoList = new ArrayList<ConfigMemento>();

    private Map<String, ConfigMemento> configMementoMap = new ConcurrentHashMap<String, ConfigMemento>();

    /**
     * 添加备忘录
     *
     * @param memento
     */
    public void append(ConfigMemento memento) {
        mementoList.add(memento);
        configMementoMap.put(memento.getConfigFile().getVersionNo(), memento);
        cursorIdx++;
    }

    /**
     * 回滚
     *
     * @return
     */
    public ConfigMemento undo() {
        //如果cursorId小于等于0，直接返回第一个备忘录
        if (--cursorIdx <= 0) {
            return mementoList.get(0);
        }
        return mementoList.get(cursorIdx);
    }

    /**
     * 返回
     *
     * @return
     */
    public ConfigMemento redo() {
        if (++cursorIdx > mementoList.size()) {
            return mementoList.get(mementoList.size() - 1);
        }
        return mementoList.get(cursorIdx);
    }

    /**
     * 定向获取
     * @param version
     * @return
     */
    public ConfigMemento get(String version){
        return  configMementoMap.get(version);
    }

}
